package com.gugee.common.thread;

import io.netty.util.concurrent.DefaultThreadFactory;

import java.util.concurrent.*;
import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory;

public class ThreadPoolUtils {

    private ThreadPoolUtils() {
    }

    public static ForkJoinPool forkJoinPool(int parallelism, String name) {
        return new ForkJoinPool(parallelism, new NamedForkJoinWorkerThreadFactory(name), null, true);
    }

    public static ThreadPoolExecutor namedFixedThreadPool(int parallelism, String name) {
        return new ThreadPoolExecutor(
                parallelism, parallelism, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
                new DefaultThreadFactory(name));
    }

    private static class NamedForkJoinWorkerThreadFactory implements ForkJoinWorkerThreadFactory {

        NamedForkJoinWorkerThreadFactory(String name) {
            this.name = name;
        }

        private String name;

        @Override
        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
            ForkJoinWorkerThread workerThread = ForkJoinPool.defaultForkJoinWorkerThreadFactory
                    .newThread(pool);
            workerThread.setName(name + "-" + workerThread.getPoolIndex());
            return workerThread;
        }
    }

}
